package org.example.service;

import demo.test.HelloResponse;
import demo.test.InstanceServiceGrpc;
import io.grpc.Status;
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;

/**
 * @Author wangjun
 * @Date 2025/3/17 18:34
 */
@GrpcService
public class GrpcServerServiceImpl extends InstanceServiceGrpc.InstanceServiceImplBase {

    @Override
    public void errorSayHello(demo.test.HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
        String message = "服务端error返回，请求参数:" + request.getName();
        try {
            int i = 10 / 0;
            demo.test.HelloResponse response = demo.test.HelloResponse.newBuilder().setMessage(message).build();
            responseObserver.onNext(response);
            responseObserver.onCompleted();
        } catch (Exception e) {
            // 关键点：使用 StatusException 或 StatusRuntimeException 包装错误
            responseObserver.onError(Status.INTERNAL.withDescription(e.getMessage()).withCause(e).asRuntimeException());
        }
    }

    @Override
    public void sayHello(demo.test.HelloRequest request, StreamObserver<demo.test.HelloResponse> responseObserver) {
        String message = "服务端返回，请求参数:" + request.getName();
        demo.test.HelloResponse response = demo.test.HelloResponse.newBuilder().setMessage(message).build();
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }
}
